//
//  CLChatStartView.swift
//  ChatDemo
//
//  Created by 范强伟 on 2024/5/16.
//

import UIKit

class CLChatStartView: UIView {

    /// 时候可以发送录音
    var isCanSendCallBack: ((Bool) -> Void)?
//    /// 开始录音
    var startRecorderCallBack: (() -> Void)?
    /// 取消录音
    var cancelRecorderCallBack: (() -> Void)?
//    /// 结束录音
    var finishRecorderCallBack: ((TimeInterval, String) -> Void)?
//    /// 是否正在录制
    private(set) var isRecording: Bool = false
    /// 是否可以发送
    private var isCanSend: Bool = true {
        didSet {
            if isCanSend != oldValue {
                isCanSendCallBack?(isCanSend)
            }
        }
    }
     
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.layer.addSublayer(bottomLayer)
        return view
    }()
    
    lazy var recordImg: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "chat_shengyinb")
        return view
    }()
    
    lazy var tipLab: UILabel = {
        let view = UILabel()
        view.font = .mediumPingFangSC(16)
        view.textColor = .white
        view.text = "松开 发送"
        view.textAlignment = .center
        return view
    }()
    
    lazy var closeImg: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "chat_quxiao_black")
        return view
    }()
    
    lazy var volumeView: CLChatVolumeView = {
        let view = CLChatVolumeView()
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .init("#000000", alpha: 0.3)
        
        makeUI()
    }

    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func makeUI(){
        addSubview(bottomView)
        addSubview(recordImg)
        addSubview(tipLab)
        addSubview(closeImg)
        
        addSubview(volumeView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(120)
        }
        
        recordImg.snp.makeConstraints { make in
            make.center.equalTo(bottomView)
            make.size.equalTo(CGSize(width: 24, height: 32))
        }
        
        tipLab.snp.makeConstraints { make in
            make.bottom.equalTo(bottomView.snp.top).offset(-8)
            make.centerX.equalToSuperview()
            make.height.equalTo(22)
        }
        
        closeImg.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(tipLab.snp.top).offset(-15)
            make.size.equalTo(36)
        }
        
        volumeView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: 120, height: 40))
        }
        
        startRecord()
        
       
    }
    
    
   class func showRecordView(complate:@escaping((Bool)->())) ->CLChatStartView{
        let v = CLChatStartView()
        v.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
        v.isCanSendCallBack = complate
        mWindow()?.addSubview(v)
//       v.becomeFirstResponder()
        return v
    }
  
    
    func touchesMoved(point: CGPoint) {
        if point.y > (screenHeight - safeAreaInsets.bottom - 49) {
//            bottomView.backgroundColor = .white
            bottomLayer.fillColor = UIColor.white.cgColor
            recordImg.image = UIImage(named: "chat_shengyinb")
            tipLab.textColor = .white
            closeImg.image = UIImage(named: "chat_quxiao_black")
            tipLab.text = "松开 发送"
        }else{
            bottomLayer.fillColor = UIColor.black.cgColor
            recordImg.image = UIImage(named: "chat_shengyinw")
            tipLab.textColor = .red
            closeImg.image = UIImage(named: "chat_quxiao_red")
            tipLab.text = "松开 取消"
        }
    }
    
    func touchEnd(point: CGPoint){
        if point.y > (screenHeight - safeAreaInsets.bottom - 49) {
             isCanSend = true
        }else{
            isCanSend = false
        }
        endRecord()
        self.removeFromSuperview()
    }
    
    lazy var bottomLayer:CAShapeLayer = {
       let view = CAShapeLayer()
        let bezierPath = UIBezierPath()
        bezierPath.move(to: CGPointMake(0, 35.0))
        bezierPath.addQuadCurve(to: CGPointMake(screenWidth, 35.0), controlPoint: CGPointMake(screenWidth/2.0, -35.0))
        bezierPath.addLine(to: CGPointMake(screenWidth, 120))
        bezierPath.addLine(to: CGPointMake(0, 120))
        view.path = bezierPath.cgPath
        view.strokeColor = UIColor.clear.cgColor
        view.fillColor = UIColor.white.cgColor
        view.cornerRadius = 3.0
        view.masksToBounds = false
        view.shadowOffset = CGSize(width: -5, height: -5)
        view.shadowColor = UIColor.gray.cgColor
        view.shadowOpacity = 0.1
        
        return view
    }()
     
    
    /// 录音器
    private lazy var recorder: CLRecorder = {
        let recorder = CLRecorder()
        recorder.durationCallback = { [weak self] second in
            guard let self = self else { return }
             
            
        }
        recorder.finishCallBack = { [weak self] duration, path in
            self?.finishRecorderCallBack?(TimeInterval(duration), path)
        }
//        recorder.volumeCallback = { [weak self] obj in
//            guard let weakself = self else { return }
//            
//        }
        return recorder
    }()
    
    
    
   
    private func startRecord() {
         
//        RRecordManager.shareManager().startRecord()
        
        if CLPermissions.isAllowed(.microphone) {
//            myRecorder.beginRecordVoice()
            recorder.start()
            startRecorderCallBack?()
//            
        } else {
            CLPermissions.request(.microphone) { status in
                if status.isNoSupport {
                    CLPopoverManager.showOneAlert(title: "当前设备不支持")
                } else if status.isAuthorized {
                } else {
                    CLPopoverManager.showTwoAlert(title: "APP 需要访问麦克风才能录制语音消息\n\n请前往「设置—隐私—麦克风」中打开开关。", right: "设置", rightCallBack: {
                        openSettings()
                    })
                }
            }
        }
    }

    private func cancelRecord() {
//        myRecorder.endRecordVoice()
        recorder.cancel()
        cancelRecorderCallBack?()
//        RRecordManager.shareManager().stopRecord()
    }

    private func endRecord() {
//        myRecorder.endRecordVoice()
        recorder.stop()
//        RRecordManager.shareManager().stopRecord()
    }
    
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
